﻿using RemoteDesktopLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteDesktopServer
{
    public partial class frmLogin : Form
    {
        private ViewerService.ViewerClient _viewerClient;
        private ScreenCapture capture = new ScreenCapture();
        private Thread _threadScreen = null;
        private bool _stop = false;
        public int _numByteFullScreen = 1;
        private ServiceHost host;

        public frmLogin()
        {
            InitializeComponent();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            IPHostEntry iphost;
            iphost = Dns.GetHostEntry(Dns.GetHostName());
            lblClientIP.Text = iphost.AddressList.
                FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (txtClientIP.Text.Equals(""))
            {
                MessageBox.Show("Bạn chưa nhập IP của client", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnConnect.Enabled = false;
            this.WindowState = FormWindowState.Minimized;

            Uri baseAddress = new Uri("http://localhost:8733/Rlc/Server");
            host = new ServiceHost(typeof(Server), baseAddress);
            try
            {
                host.Open();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "frmLogin.cs - Line 54.");
            }

            EndpointAddress endAddr = new EndpointAddress("http://" + txtClientIP.Text + ":6971/Rlc/Viewer");
            BasicHttpBinding binding = new BasicHttpBinding();
            binding.Name = "BasicHttpBinding_IViewer";
            binding.MessageEncoding = WSMessageEncoding.Mtom;
            _viewerClient = new ViewerService.ViewerClient(binding, endAddr);

            _threadScreen = new Thread(new ThreadStart(ScreenThread));
            _threadScreen.Start();
        }

        private void ScreenThread()
        {
            Rectangle bounds = Rectangle.Empty;

            while (!_stop)
            {
                try
                {
                    Bitmap image = capture.Screen(ref bounds);
                    if (_numByteFullScreen == 1)
                    {
                        // Tính toán kích thước phần thay đổi theo byte (dùng cho phần hiển thị thông số)
                        _numByteFullScreen = bounds.Width * bounds.Height * 4;
                    }
                    if (bounds != Rectangle.Empty && image != null)
                    {
                        byte[] data = Utils.PackScreenCaptureData(image, bounds);
                        if (data != null)
                        {
                            lock (_viewerClient)
                            {
                                try
                                {
                                    _viewerClient.PushScreenUpdate(data);
                                    //Tính toán hiển thị bộ đếm
                                    double perc1 = 100.0 * 4.0 * image.Width * image.Height / _numByteFullScreen;
                                    double perc2 = 100.0 * data.Length / _numByteFullScreen;
                                    this.Invoke(new MethodInvoker(delegate
                                    {
                                        listBox1.Items.Add(String.Format(DateTime.Now.ToString() + ": Screen - {0:0.0} percent, {1:0.0} percent with compression", perc1, perc2));
                                        this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1;
                                        // load the control with the appropriate data
                                    }));
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex, "No connection...trying again in 5 seconds");        
                                    RefreshConnection();
                                    Thread.Sleep(5000);
                                }
                            }
                        }
                        else
                        {
                            // Show performance metrics.
                            //
                            Logger.Info(DateTime.Now.ToString(), "No data change...");        
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Unhandled error");
                }
            }
        }

        private void RefreshConnection()
        {
            EndpointAddress endAddr = new EndpointAddress("http://" + txtClientIP.Text + ":6971/Rlc/Viewer");
            BasicHttpBinding binding = new BasicHttpBinding();
            binding.Name = "BasicHttpBinding_IViewer";
            binding.MessageEncoding = WSMessageEncoding.Mtom;
            _viewerClient = new ViewerService.ViewerClient(binding, endAddr);

            capture.Reset();
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            _stop = true;
        }

        private void txtClientIP_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 46 || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

    }
}
